package com.sxfq.loansupermarket.backsystem.modular.report.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.report.entity.CashDailyReportInfo;
import com.sxfq.loansupermarket.backsystem.modular.report.entity.SearchCashDailyReportInfo;
import com.sxfq.loansupermarket.backsystem.modular.report.service.ICashDailyReportService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 现金日报
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/cashDailyReport")
public class CashDailyReportController extends BaseController {

    @Autowired
    ICashDailyReportService service;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/report/wholeHospital/";

    /**
     * 跳转到预约客户管理页面
     */
    @RequestMapping("")
    public String cashDailyReport(Model model) {
        return PREFIX + "/cash_daily_report.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object cashDailyReportList(SearchCashDailyReportInfo info, HttpServletRequest request) {
        Page<CashDailyReportInfo> page = new PageFactory<CashDailyReportInfo>().defaultPage();
        try {
            String tableHead = ShiroKit.getUser().getAbbreviation();
            String tableName = tableHead + "recharge_info";
            String sql ="update "+tableName+" a set a.recharges_time=left( DATE_ADD(a.recharge_time,INTERVAL 1 DAY) ,10) " +
                    " where right(a.recharge_time,8)>= '16:00:00' and a.recharges_time is null;";
            sqlMapper.update(sql);

            String sql2 ="update "+tableName+" a set a.recharges_time=left(a.recharge_time,10) " +
                    " where right(a.recharge_time,8)<'16:00:00' and a.recharges_time is null;";
            sqlMapper.update(sql2);

            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<CashDailyReportInfo> list = service.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListByQueryGetMap(page, info);
            }
            page.setTotal(service.getQueryPagesCount(page, info) + 1);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    @RequestMapping(value = "/cashDailyReportExport")
    public void cashDailyReportExport(@RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime,
                                      HttpServletResponse response) {
        try {
            SearchCashDailyReportInfo searchInfo = new SearchCashDailyReportInfo();
            searchInfo.setStartTime(startTime);
            searchInfo.setEndTime(endTime);
            List<CashDailyReportInfo> list = service.cashDailyReportExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 19; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("日期");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("日总收入");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("现金");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("随行付");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("华夏刷卡");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("医保");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("美团");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("荣华");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("百度钱包");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("华银百汇扫码");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("糯米");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("天猫");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("备注");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                CashDailyReportInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                String rechargeTime = map.getRechargeTime();
                String totalDailyIncome = map.getTotalDailyIncome();
                String cash = map.getCash();
                String followUp = map.getFollowUp();
                String huaXiaCard = map.getHuaXiaCard();
                String medicalInsurance = map.getMedicalInsurance();
                String meiTuan = map.getMeiTuan();
                String huaRong = map.getHuaRong();
                String baiduPurse = map.getBaiduPurse();
                String huaYinBaiHui = map.getHuaYinBaiHui();
                String glutinousRice = map.getGlutinousRice();
                String tmall = map.getTmall();
                String remark = map.getRemark();
                if (StringUtil.isEmpty(totalDailyIncome)) {
                    totalDailyIncome = "0.00";
                }
                if (StringUtil.isEmpty(cash)) {
                    cash = "0.00";
                }
                if (StringUtil.isEmpty(followUp)) {
                    followUp = "0.00";
                }
                if (StringUtil.isEmpty(huaXiaCard)) {
                    huaXiaCard = "0.00";
                }
                if (StringUtil.isEmpty(medicalInsurance)) {
                    medicalInsurance = "0.00";
                }
                if (StringUtil.isEmpty(meiTuan)) {
                    meiTuan = "0.00";
                }
                if (StringUtil.isEmpty(huaRong)) {
                    huaRong = "0.00";
                }
                if (StringUtil.isEmpty(baiduPurse)) {
                    baiduPurse = "0.00";
                }
                if (StringUtil.isEmpty(huaYinBaiHui)) {
                    huaYinBaiHui = "0.00";
                }
                if (StringUtil.isEmpty(glutinousRice)) {
                    glutinousRice = "0.00";
                }
                if (StringUtil.isEmpty(tmall)) {
                    tmall = "0.00";
                }
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 13; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                Double totalDailyIncomes = new Double(String.valueOf(totalDailyIncome));
                Double cashs = new Double(String.valueOf(cash));
                Double followUps = new Double(String.valueOf(followUp));
                Double huaXiaCards = new Double(String.valueOf(huaXiaCard));
                Double medicalInsurances = new Double(String.valueOf(medicalInsurance));
                Double meiTuans = new Double(String.valueOf(meiTuan));
                Double huaRongs = new Double(String.valueOf(huaRong));
                Double baiduPurses = new Double(String.valueOf(baiduPurse));
                Double huaYinBaiHuis = new Double(String.valueOf(huaYinBaiHui));
                Double glutinousRices = new Double(String.valueOf(glutinousRice));
                Double tmalls = new Double(String.valueOf(tmall));
                rechargeTime = rechargeTime.replaceAll("-0", "-");
                rechargeTime = rechargeTime.replaceAll("-", ".");
                //row.getCell(0).setCellValue(customerStatus);
                row.getCell(0).setCellValue(rechargeTime);
                row.getCell(1).setCellValue(totalDailyIncomes);
                row.getCell(2).setCellValue(cashs);
                row.getCell(3).setCellValue(followUps);
                row.getCell(4).setCellValue(huaXiaCards);
                row.getCell(5).setCellValue(medicalInsurances);
                row.getCell(6).setCellValue(meiTuans);
                row.getCell(7).setCellValue(huaRongs);
                row.getCell(8).setCellValue(baiduPurses);
                row.getCell(9).setCellValue(huaYinBaiHuis);
                row.getCell(10).setCellValue(glutinousRices);
                row.getCell(11).setCellValue(tmalls);
                row.getCell(12).setCellValue(remark);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

}
